package yxy.cherry.paycenter.servlet.channel.huawei;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import yxy.apple.logger.Logger;
import yxy.apple.util.Base64Utility;
import yxy.cherry.game.base.bean.SDKParm;
import yxy.cherry.game.base.bean.SdkParmEnum;
import yxy.cherry.paycenter.database.dao.orderinfoDao;
import yxy.cherry.paycenter.database.db.orderinfo;
import yxy.cherry.paycenter.servlet.channel.Servlet;
import yxy.cherry.paycenter.util.HttpUtil;
import yxy.game.pm2.bean.channel.SdkChannel;

public class Servlet_huawei extends Servlet{

	private static final Logger logger = Logger.create(Servlet_huawei.class);
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpUtil.printlnParseMap("post", req);
		
//					必选(M)/可选(O)
//		参数名称		M/O		类型					参数说明
//		data		M		DeliveryRequest		通知发货的请求信息。
//		sign		M		String				华为服务器在发送通知时对data中的所有参数使用SHA256WithRSA算法进行了签名，
//												并在sign参数中返回签名后的字符串。开发者需要使用获取验签公钥中获取的验签
//												公钥对签名字符串进行验签，验签方法参见验签示例。
		
//		DeliveryRequest
//		参数名称			M/O		类型				参数说明
//		developerId		M		String			开发者帐号的CP ID，用于唯一标识当前开发者。
//		appId			M		String			需要发货的应用ID。
//		orderId			M		String			支付订单号。
//		productNo		M		String			需要发货的商品ID。
//		openId			M		String			用户的唯一标识。如果开发者使用unionId作为用户唯一标识，
//												在获取openId后可根据openId和unionId的对应关系自行映射。
//		count			M		String			默认传1。
//		ts				M		String			通知发送时间的时间戳。
		
		JSONObject json = HttpUtil.getParseJSON(req);
		String data = json.getString("data");
		
		JSONObject datajson = json.getJSONObject("data");
		String sign = json.getString("sign");
		
		String developerId = datajson.getString("developerId");
		String appId = datajson.getString("appId");
		String orderId = datajson.getString("orderId");
		String productNo = datajson.getString("productNo");
		String openId = datajson.getString("openId");
		String count = datajson.getString("count");
		String ts = datajson.getString("ts");
		
		if(orderId == null) {
			orderinfo orderinfo = new orderinfo();
			orderinfo.setMyorderid(orderId);
			orderinfo.setOtherinfo(json.toString());
			orderinfoDao.add(orderinfo);
		}
		
		String publickey = SDKParm.getSdkparmvalue(SdkParmEnum.huawei_paypublickey);
//		String publickey = "MIIBojANBgkqhkiG9w0BAQEFAAOCAY8AMIIBigKCAYEAiAOD2dCdYKlXfrvjgTn3NzICyCRfZINmvoIF6HTYRlCeU5wYRJz8J9mdQIdZw5ps42R6fNk0NRHsxU8kMvW38BoreGypl47fkL6HlvvQXhd1gZ5mnjyxhj/OhmTstr/qJQY8+bqcyBfJolSDsszNNqsftzFCYD3WeR34HNewN1HYwq7L8sf8WUiJZGamvjvTacFlctfY49OqI+Eaf6NkEcHRTYHDfbscHF3u2lY8GegMi0XYOzoghlTlqI5guzgMHmM1BH0XREz6tEWePjx8VuT5XCWRtD7gd2i3viuuu8Juk9jQpsL7hiMGE1wIsPH2M5xPPnI7K5r53DOzdwYmu1/aUv+Ex0AKXM7h5QgnDUvnmmYDb4Ki5+yp9x4X2hod8+0+zFF6J5RHMJyCiLsJvQiwnGvyUJ/l12ao0mt3Dm+v3x2f1UlPbUxxbvTnR1NAZ9e0CaB74dvzXPdCcirXEtnM1CCuoGK2w/1u7KAEZTQkpSQuvUdFge7XfT/gFxhnAgMBAAE=";
		boolean bverify = doCheck(data, sign, publickey);
		if(!bverify) {
			logger.info("sdk_huawei verify false");
			JSONObject rjson = new JSONObject();
			JSONObject errorjson = new JSONObject();
			errorjson.put("errorCode", 0);
			errorjson.put("errorMsg", "sign verify fail");
			rjson.put("error", errorjson);
			returnInfo(rjson, resp);
			return;
		}
	}

	/** *校验签名信息  
	* @param content 待校验字符串，传入请求参数data的json字符串。
	* @param sign 签名字符串  
	* @param publicKey 验签公钥  
	* @param 是否校验通过  
	*/ 
	public static boolean doCheck(String content, String sign, String publicKey) { 
	   try { 
	      KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 
	      byte[] encodedKey = Base64Utility.decode(publicKey.getBytes()); 
	      PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); 
	      Signature signature = null; 
	      signature = Signature.getInstance("RSA"); 
	      signature.initVerify(pubKey); 
	      signature.update(content.getBytes("utf-8")); 
	      boolean bverify = signature.verify(Base64Utility.decode(sign.getBytes())); 
	      return bverify; 
	   } catch (Exception e) { 
	      e.printStackTrace(); 
	   } 
	   return false; 
	}
	
	@Override
	public String getChannel() {
		return SdkChannel.sdk_huawei;
	}
}
